package multiThred;

public class MultiThreadPrintABC {
    private static final Object lock = new Object();
    private static int state = 0; // 用于控制打印顺序，0表示A，1表示B，2表示C

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> print("A", 0));
        Thread threadB = new Thread(() -> print("B", 1));
        Thread threadC = new Thread(() -> print("C", 2));

        threadA.start();
        threadB.start();
        threadC.start();
    }

    private static void print(String name, int targetState) {
        for (int i = 0; i < 10; i++) { // 每个线程打印10次
            synchronized (lock) {
                while (state != targetState) {
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(name);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                state = (state + 1) % 3; // 状态切换到下一个线程
                lock.notifyAll(); // 唤醒其他等待线程
            }
        }
    }
}
